<?php

namespace App\Listeners;

use App\Events\OrderShipped;
use App\Models\PunchCardAdmin;
use App\Models\PunchCardUser;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use EasyWeChat\Factory;
use Exception;

class SendShipmentNotification
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  OrderShipped  $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        try {
            $recordInfo = $event->record;
            if ($recordInfo instanceof PunchCardUser) {
                $userInfo = $recordInfo;
            } else {
                $userInfo = $recordInfo->users;
            }

            $app = Factory::officialAccount(config('wechat.official_account.default'));
            $app['access_token']->setToken(get_url_token());
            PunchCardAdmin::where('status', 1)->get()->each(function ($item) use ($app, $recordInfo, $userInfo) {
                $result = $app->template_message->send([
                    'touser' => $item->openid,
                    'template_id' => 'zsybJn0m-flFFGlOu09y2bFDytdNA-HG4kglmU1QZHY',
                    'url' =>  isset($userInfo->punch_num) ? route('punch.card.remark', ['record' => $recordInfo->id]) : route('punch.card.open.card', ['user' => $userInfo->id]),
                    // 'miniprogram' => [
                    //     'appid' => 'xxxxxxx',  
                    //     'pagepath' => 'pages/xxx',
                    // ],
                    'data' => [
                        'first' => isset($userInfo->punch_num) ? '客户' . $userInfo->nickname . '已登记' : '客户' . $userInfo->nickname . '首次扫码',
                        'keyword1' => $userInfo->openid,
                        'keyword2' => $userInfo->name,
                        'keyword3' => $recordInfo->created_at,
                        'remark' => isset($userInfo->punch_num) ? '请赶快备注信息' : '请赶快开卡',
                    ],
                ]);
                // info($result);
            });
        } catch (\Exception $e) {
            info($e->getMessage());
        }
    }
}
